package com.talkyun.openx.ocean.proxy;

import com.talkyun.ocean.RegistryClient;
import com.talkyun.ocean.model.Endpoint;
import com.talkyun.openx.client.RestfulJsonProxy;

import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.List;

public class RegistryableRandomProxy extends RestfulJsonProxy {
    private SecureRandom random = new SecureRandom();
    private RegistryClient client;

    RegistryableRandomProxy(RegistryClient client, Class<?> api) {
        this.client = client;
        super.setApiClass(api);
    }

    @Override
    public String toString() {
        String registryUrl = client.getRegistryUrl();
        return api == null ? "null" : api.getName() + "(rc:" + registryUrl + ")";
    }

    @Override
    protected Object doInvoke(Object proxy, Method method, Object[] args) throws Exception {
        String url = this.getServiceUrl() + "/" + method.getName();
        return super.doInvoke(url, proxy, method, args);
    }

    private String getServiceUrl() {
        List<Endpoint> list = client.listEndpoint(super.getApiClass());
        if (list.isEmpty()) {
            throw new RuntimeException("No any service endpoint! " + getApiClass().getName());
        }
        Endpoint e = list.get(random.nextInt(list.size()));
        return e.toUrl();
    }
}
